<template>
  <div class="background">
    <div class="register-container fade-in-animation">
      <h1 class="form-title">注册</h1>
      <el-form ref="registerForm" :model="registerForm" :rules="rules" class="form">
        <!-- 用户名和昵称 -->
        <div class="form-row">
          <el-form-item label="账号" prop="userName" class="form-item">
            <el-input
                class="input"
                v-model="registerForm.userName"
                ref="userName"
                placeholder="请输入账号"
                autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="昵称" prop="nickName" class="form-item" >
            <el-input
                class="input"
                v-model="registerForm.nickName"
                ref="nickName"
                placeholder="请输入昵称"
                autocomplete="new-password"
            ></el-input>
          </el-form-item>
        </div>

        <!-- 密码和确认密码 -->
        <div class="form-row">
          <el-form-item label="密码" prop="password" class="form-item">
            <div class="password-input-wrapper">
            <el-input
                class="input"
                :type="passwordVisible_one ? 'text' : 'password'"
                v-model="registerForm.password"
                ref="password"
                placeholder="密码至少为8位，含大小写字母和数字"
                autocomplete="new-password"
            ></el-input>
            <button
                type="button"
                class="toggle-password-button"
                @click="togglePasswordVisibility_one"
            >
              <i :class="passwordVisible_one ? 'el-icon-view' : 'el-icon-view-off'"></i>
            </button>
        </div>
          </el-form-item>
          <el-form-item label="确认密码" prop="confirmPassword" class="form-item">
            <div class="password-input-wrapper">
            <el-input
                class="input"
                :type="passwordVisible_two ? 'text' : 'password'"
                v-model="registerForm.confirmPassword"
                ref="confirmPassword"
                placeholder="请确认密码"
                autocomplete="off"
            ></el-input>
            <button
                type="button"
                class="toggle-password-button"
                @click="togglePasswordVisibility_two"
            >
              <i :class="passwordVisible_two ? 'el-icon-view' : 'el-icon-view-off'"></i>
            </button>
        </div>
          </el-form-item>
        </div>

        <!-- 邮箱 -->
        <div class="form-row">
          <el-form-item label="邮箱/手机号" prop="email" class="form-item">
            <el-input
                class="input"
                v-model="registerForm.email"
                ref="email"
                placeholder="请输入邮箱/手机号"
                autocomplete="off"
            ></el-input>
          </el-form-item>
        </div>

        <!-- 验证码 -->
        <div class="form-row">
          <el-form-item label="验证码" prop="verificationCode" class="form-item">
            <div class="verification-wrapper">
              <el-input
                  class="input verification-input"
                  v-model="registerForm.verificationCode"
                  ref="verificationCode"
                  placeholder="请输入验证码"
                  autocomplete="off"
              ></el-input>
              <el-button
                  class="verification-button"
                  type="primary"
                  :disabled="isSending"
                  @click="sendVerificationCode"
              >
                {{ buttonLabel }}
              </el-button>
            </div>
          </el-form-item>
        </div>

        <!-- 用户类型 -->
        <div class="form-row">
          <el-form-item label="用户类型" prop="userType" class="form-item">
            <el-select
                v-model="registerForm.userType"
                placeholder="请选择用户类型"
                class="input"
                @change="handleUserTypeChange"
            >
              <el-option label="普通成员" value="2"></el-option>
              <el-option label="组长" value="1"></el-option>
            </el-select>
          </el-form-item>
        </div>

        <!-- 职务 -->
        <div class="form-row" v-if="registerForm.userType === '2'">
          <el-form-item label="职务" prop="role" class="form-item">
            <el-select
                v-model="registerForm.role"
                placeholder="请选择职务"
                class="input"
            >
              <el-option label="前端" value="前端"></el-option>
              <el-option label="后端" value="后端"></el-option>
              <el-option label="运维" value="运维"></el-option>
              <el-option label="测试" value="测试"></el-option>
            </el-select>
          </el-form-item>
        </div>

        <!-- 确认和取消按钮 -->
        <div class="form-row">
          <el-button type="primary" block class="button confirm-button" @click="register">
            确认
          </el-button>
        </div>
        <div class="form-row">
          <el-button type="default" block class="button cancel-button" @click="$router.push('/Login')">
            取消
          </el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script>
import axios from "axios";

export default {
  name: "RegisterView",
  data() {
    return {
      registerForm: {
        userName: "",
        password: "",
        confirmPassword: "",
        nickName: "",
        email: "",
        verificationCode: "",
        userType: "",
        role: "",
      },
      rules: {
        userName: [{ required: true, message: "账号不能为空", trigger: "blur" }],
        password: [{ required: true, message: "密码不能为空", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              const passwordPattern = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$/;
              if (!passwordPattern.test(value)) {
                callback(new Error("密码至少为8位且包含数字和大小写字母"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
          ],
        confirmPassword: [{ required: true, message: "请再次输入密码", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (value !== this.registerForm.password) {
                callback(new Error("两次密码输入不一致"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        nickName: [{ required: true, message: "昵称不能为空" }],
        email: [
          { required: true, message: "邮箱/手机号不能为空" },
          {
            validator: (rule, value, callback) => {
              const emailRegex = /^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/;
              const phoneRegex = /^[1][3-9][0-9]{9}$/;
              if (!emailRegex.test(value) && !phoneRegex.test(value)) {
                callback(new Error("请输入有效的邮箱或手机号"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        verificationCode: [{ required: true, message: "验证码不能为空" }],
        userType: [{ required: true, message: "请选择用户类型" }],
        role: [{ required: true, message: "请选择职务", trigger: "change" }],
      },
      isSending: false,
      countdown: 0,
      passwordVisible_one: false,
      passwordVisible_two: false
    };
  },
  created() {
    // 在组件加载时清空表单数据，确保所有字段为空
    this.resetForm();
  },
  computed: {
    buttonLabel() {
      return this.isSending ? `${this.countdown}秒后重新发送` : "发送验证码";
    },
  },
  methods: {
    togglePasswordVisibility_one() {
      this.passwordVisible_one = !this.passwordVisible_one;
    },
    togglePasswordVisibility_two() {
      this.passwordVisible_two = !this.passwordVisible_two;
    },
    handleUserTypeChange(value) {
      if (value !== "2") {
        this.registerForm.role = "";
      }
    },
    sendVerificationCode() {
      if (this.registerForm.email.trim() === "") {
        this.$message.error("请输入邮箱/手机号");
        return;
      }

      axios
          .post("http://localhost:8095/user/sendVerificationCode", {
            email: this.registerForm.email,
          })
          .then((response) => {
            if (response.data.code === 200) {
              this.$message.success("验证码已发送到您的邮箱");
              this.startCountdown();
            } else {
              this.$message.error("发送验证码失败");
            }
          })
          .catch((error) => {
            console.error(error);
            this.$message.error("发送验证码失败");
          });
    },
    startCountdown() {
      this.isSending = true;
      this.countdown = 60;
      let timer = setInterval(() => {
        this.countdown--;
        if (this.countdown <= 0) {
          clearInterval(timer);
          this.isSending = false;
        }
      }, 1000);
    },
    register() {
      this.$refs.registerForm.validate((valid) => {
        if (valid) {
          /*if (this.registerForm.password !== this.registerForm.confirmPassword) {
            this.$message.error("密码和确认密码不一致");
            return;
          }*/
          axios
              .post("http://localhost:8095/user/register", this.registerForm)
              .then((response) => {
                if (response.data.code === 200) {
                  this.$message.success("注册成功");
                  this.$router.push("/Login");
                } else {
                  this.$message.error("注册失败");
                }
              })
              .catch((error) => {
                console.log(error);
              });
        }
      });
    },
  },
};
</script>

<style scoped>
.background {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: url("@/assets/background/background02.jpeg") no-repeat center center/cover;
}

.register-container {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20px;
  box-shadow: 0 15px 30px rgba(0, 0, 0, 0.2);
  padding: 20px;
  width: 90%;
  max-width: 650px;
}

.fade-in-animation{
  animation: fadeIn 0.8s ease-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.form-title {
  font-size: 24px;
  margin-bottom: 15px;
  color: #333;
  text-align: center;
}

.form-row {
  display: flex;
  gap: 15px;
  margin-bottom: 15px;
}

.form-item {
  flex: 1;
}

.verification-wrapper {
  display: flex;
  align-items: center;
  gap: 10px; /* 控制输入框和按钮之间的间距 */
}

.verification-input {
  flex: 2; /* 输入框占较大宽度 */
}

.verification-button {
  flex: 1; /* 按钮占剩余宽度 */
  height: 40px; /* 保持与输入框一致高度 */
}

.input {
  width: 100%;
}

.button-group {
  margin-top: 15px;
}

.confirm-button,
.cancel-button {
  width: 100%;
  margin: 5px 0;
}

/* 密码输入框容器 */
.password-input-wrapper {
  display: flex;
  align-items: center;
  position: relative;
}

.toggle-password-button {
  position: absolute;
  right: 10px;
  background: none;
  border: none;
  cursor: pointer;
  font-size: 18px;
  color: #888;
}

.toggle-password-button:hover {
  color: #555;
}
</style>
